mui.init();

function foreach(array, func) {
	for (var i = 0; i < array.length; ++i) {
		func(array[i]);
	}
}

function clean() {	
	document.getElementById('tip').style.display = 'none';
	foreach(document.getElementsByClassName('forward'), function(each) {
		each.style.display = 'none';
	});
	foreach(document.getElementsByClassName('backward'), function(each) {
		each.style.display = 'none';
	});
}

function update(bus) {
	var show = document.getElementById('content');
	var icon = document.getElementById('icon');
	icon.className = icon.className.replace('mui-icon-loop', 'mui-icon-spinner');
	
	var Bus = {
		New: function(busStop, state) {
			var bus = {};
			bus.busStop = busStop;
			bus.state = state === '行驶' ? true : false;
			return bus;
		}
	};
	
	var Route = {
		New: function(direction) {
			var route = {};
			route.direction = direction;
			route.buses = new Array();
			return route;
		}
	}
	
	mui.ajax('http://27.154.226.150:9002/bus/Bus_Pos_Curr.aspx', {
		data: {
			__VIEWSTATE: '/wEPDwUKLTMzNDA4MjY2MQ9kFgICAw9kFgQCAQ8QDxYEHg1EYXRhVGV4dEZpZWxkBQlyb3V0ZWNvZGUeC18hRGF0YUJvdW5kZ2QQFScBMQIxMAIxMQIxMgIxMwUxNDowOAIxOAMyMDEDMjAyBDIwM0IDMjA1AzIwNgMyMDcDMjA4AzIwOQMyMTADMjExAzIxMgMyMTMBMwMzMDEDMzAyAzMwMwMzMDUDMzA2BDMwNkIDMzA3AzMwOAMzMDkDMzExAzMxMgMzMTMDMzE1ATUBNgE3ATgBOQnmnLrliqjovaYVJwExAjEwAjExAjEyAjEzBTE0OjA4AjE4AzIwMQMyMDIEMjAzQgMyMDUDMjA2AzIwNwMyMDgDMjA5AzIxMAMyMTEDMjEyAzIxMwEzAzMwMQMzMDIDMzAzAzMwNQMzMDYEMzA2QgMzMDcDMzA4AzMwOQMzMTEDMzEyAzMxMwMzMTUBNQE2ATcBOAE5CeacuuWKqOi9phQrAydnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dkZAIFDzwrAA0AZBgBBQlHcmlkVmlldzEPZ2R/xirhH1yVD7vyxauO01WIwXLHOw==',
			__EVENTVALIDATION: '/wEWKQKgtIbjDQKSi6WLBgKSi+WIBgKSi+mIBgKSi+2IBgKSi9GIBgL4+Or+BAKSi4WLBgLe86SqDwLD5MaBBQLkjbHoDAKy2K3BBALXwc/cAgL46tGrCALNgJF1Avaps8AOArXKht8BAt7zqKoPAsPkyoEFAuSN7ZwDApCLpYsGAt/zpKoPAsDkxoEFAuWN6ZwDArPYrcEEAtTBz9wCAtTBl6gOAvnq0asIAtKAkXUC96mzwA4C3/Ooqg8CwOTKgQUC5Y3tnAMCs9iRwQQClouliwYCl4uliwYClIuliwYChYuliwYCiouliwYC3/OsFwKM54rGBqcxCq2Wi1+/VrqecQBr8vK7yR+a',
			DropDownList1: document.getElementById('select').value,
			Button1: ''
		},
		type: 'POST',
		timeout: 5000,
		dataType: 'html',
		
		success: function(response) {
			var data = (function() {
				// Get Table
				var doc = document.createElement('div');
				doc.innerHTML = response;
				var t = doc.childNodes[3].childNodes[5].childNodes[1].childNodes[1].childNodes[4].childNodes[1].childNodes[1].childNodes[1];

				// Create Data Result
				forward = Route.New(null);
				backward = Route.New(null);
				if (t != null) {
					for (var i = 1; i < t.rows.length; ++i) {
						var s = t.rows[i].cells;
						if (s[1].innerText === forward.direction) {
							forward.buses.push(Bus.New(s[2].innerText, s[3].innerText));
						} else if (s[1].innerText === backward.direction) {
							backward.buses.push(Bus.New(s[2].innerText, s[3].innerText));
						} else if (forward.direction === null) {
							forward.direction = s[1].innerText;
							forward.buses.push(Bus.New(s[2].innerText, s[3].innerText));
						} else {
							backward.direction = s[1].innerText;
							backward.buses.push(Bus.New(s[2].innerText, s[3].innerText));
						}
					}
					return { forward: forward, backward: backward };
				} else {
					return null;
				}
			})();
			
			clean();
			
			// Show new data
			if (data === null) { // No bus
				document.getElementById('tip').style.display = 'block';
			} else {
				if (data.forward.direction !== null) {
					foreach(document.getElementsByClassName('forward'), function(each) {
						each.style.display = 'block';
					});
					mui('h4.forward')[0].innerHTML = data.forward.direction.replace('->', '<span class="mui-icon mui-icon-arrowright"></span>');
					var list = mui('ul.forward')[0];
					list.innerHTML = '';
					foreach(data.forward.buses, function(each) {
						var item = document.createElement('li');
						item.className = 'mui-table-view-cell';
						item.innerHTML = each.busStop + '<span class="mui-pull-right iconfont icon-bus-' + (each.state ? 'run' : 'stop') + '"></span>';
						list.appendChild(item);
					});
				}
				if (data.backward.direction !== null) {
					foreach(document.getElementsByClassName('backward'), function(each) {
						each.style.display = 'block';
					});
					mui('h4.backward')[0].innerHTML = data.backward.direction.replace('->', '<span class="mui-icon mui-icon-arrowright"></span>');
					var list = mui('ul.backward')[0];
					list.innerHTML = '';
					foreach(data.backward.buses, function(each) {
						var item = document.createElement('li');
						item.className = 'mui-table-view-cell';
						item.innerHTML = each.busStop + '<span class="mui-pull-right iconfont icon-bus-' + (each.state ? 'run' : 'stop') + '"></span>';
						list.appendChild(item);
					});
				}
			}

			// Update Icon state
			setTimeout(function(){
				icon.className = icon.className.replace('mui-icon-spinner', 'mui-icon-loop');
			}, 100);
		},
		
		error: function(xhr, type, error) {
			icon.className = icon.className.replace('mui-icon-spinner', 'mui-icon-loop');
			clean();
			mui.toast('刷新失败。请检查网络。');
		}
	});
}

function change() {
	localStorage.busIndex = document.getElementById('select').selectedIndex;
	update();
}

var firstQuit = null;
document.addEventListener('plusready', function() {
	document.getElementById('select').selectedIndex = localStorage.busIndex;
	update();

	mui.back = function() {
		if (!firstQuit) {
			firstQuit = new Date().getTime();
			mui.toast('再按一次退出');
			setTimeout(function() {
				firstQuit = null;
			}, 1500);
		} else if (new Date().getTime() - firstQuit < 1500){
			plus.runtime.quit();
		}
		return false;
	}
});
